<template>
    <div class="app-container">
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="快递编码">
                <el-input v-model="billNum" placeholder="快递编码"></el-input>
            </el-form-item>
            <el-form-item label="快递公司">
                <el-input v-model="courierCompany" placeholder="快递公司"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchInfo()">查询</el-button>
            </el-form-item>
        </el-form>

        <!-- :data 绑定页面显示的数据的列表
        prop 绑定的数据的名称
        -->
        <el-table :data="list" v-loading="listLoading" element-loading-text="Loading" stripe style="width: 100%">
            <el-table-column type="index" :index="indexMethod" label="行号">
            </el-table-column>
            <el-table-column prop="courierCompany" label="快递公司" width="120">
            </el-table-column>
            <el-table-column prop="pickupAddress" label="代取地址" width="120">
            </el-table-column>
            <el-table-column prop="deliveryAddress" label="收货地址" width="120">
            </el-table-column>
            <el-table-column prop="deliveryTime" label="配送时间" width="180">
            </el-table-column>
            <el-table-column prop="deliveryPersonName" label="配送人" width="80">
            </el-table-column>
            <el-table-column prop="deliveryPersonPhone" label="配送人电话">
            </el-table-column>
            <el-table-column prop="recipient" label="收货人" width="80">
            </el-table-column>
            <el-table-column prop="recipientPhone" label="收货人电话">
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <span v-if="scope.row.status === 0">未支付</span>
                    <span v-if="scope.row.status === 1">配送中</span>
                    <span v-if="scope.row.status === 2">已完成</span>
                </template>
            </el-table-column>

            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">详情</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
                        <span v-if="scope.row.status === 0">取消订单</span>
                        <span v-if="scope.row.status === 1">取消订单</span>
                        <span v-if="scope.row.status === 2">删除订单</span>
                    </el-button>
                </template>
            </el-table-column>

        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
        <!-- 订单详情弹窗 -->
        <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="800px" custom-class="order-detail-dialog">
            <el-form :model="detailForm" label-position="top" class="compact-form">
                <el-row :gutter="20">
                    <!-- 左栏 -->
                    <el-col :span="12">
                        <!-- 基础信息区块 -->
                        <div class="info-block">
                            <div class="block-header">📦 订单信息</div>
                            <el-form-item label="订单编码" class="compact-item">
                                <el-input v-model="detailForm.orderNo" readonly class="info-input" />
                            </el-form-item>

                            <el-row :gutter="15">
                                <el-col :span="12">
                                    <el-form-item label="快递编码" class="compact-item">
                                        <el-input v-model="detailForm.billNum" readonly class="info-input" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="快递公司" class="compact-item">
                                        <el-input v-model="detailForm.courierCompany" readonly class="info-input" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>

                        <!-- 配送信息区块 -->
                        <div class="info-block">
                            <div class="block-header">🚚 配送信息</div>
                            <el-form-item label="配送时间" class="compact-item">
                                <el-date-picker v-model="detailForm.deliveryTime" type="datetime" readonly
                                    class="full-width" />
                            </el-form-item>

                            <el-form-item label="代取地址" class="compact-item">
                                <el-input v-model="detailForm.pickupAddress" readonly class="info-input" type="textarea"
                                    :autosize="{ minRows: 2 }" />
                            </el-form-item>

                            <el-form-item label="配送地点" class="compact-item">
                                <el-input v-model="detailForm.deliveryAddress" readonly class="info-input"
                                    type="textarea" :autosize="{ minRows: 2 }" />
                            </el-form-item>
                        </div>
                    </el-col>

                    <!-- 右栏 -->
                    <el-col :span="12">
                        <!-- 联系人信息区块 -->
                        <div class="info-block">
                            <div class="block-header">👤 联系人信息</div>
                            <el-row :gutter="15">
                                <el-col :span="12">
                                    <el-form-item label="收货人" class="compact-item">
                                        <el-input v-model="detailForm.recipient" readonly class="info-input" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="联系电话" class="compact-item">
                                        <el-input v-model="detailForm.recipientPhone" readonly class="info-input" />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item label="配送员信息" class="compact-item">
                                <div class="delivery-info">
                                    <div class="info-tag">
                                        <span class="label">姓名：</span>
                                        <el-tag type="info">{{ detailForm.deliveryPersonName || '暂未分配' }}</el-tag>
                                    </div>
                                    <div class="info-tag">
                                        <span class="label">电话：</span>
                                        <el-tag type="info">{{ detailForm.deliveryPersonPhone || '-' }}</el-tag>
                                    </div>
                                </div>
                            </el-form-item>
                        </div>

                        <!-- 备注信息区块 -->
                        <div class="info-block">
                            <div class="block-header">📝 订单备注</div>
                            <el-form-item class="compact-item">
                                <el-input v-model="detailForm.remark" type="textarea" readonly
                                    :autosize="{ minRows: 4 }" class="remark-box" />
                            </el-form-item>
                        </div>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关闭</el-button>
                <el-button type="warning" @click="editDeliveryTime">修改时间</el-button>
                <el-button type="success" @click="sure">保存修改</el-button>
            </div>
        </el-dialog>


        <el-dialog title="修改配送时间" :visible.sync="deliveryTimeDialogVisible" width="600px" class="delivery-time-dialog">
            <el-form ref="timeForm" label-position="top">
                <el-form-item label="配送时间" class="time-picker-group" label-width="80px">
                    <el-row :gutter="15">
                        <!-- 日期选择 -->
                        <el-col :span="12">
                            <div class="picker-container">
                                <el-date-picker v-model="deliveryDate" type="date" placeholder="选择日期"
                                    :picker-options="dateOptions" value-format="yyyy-MM-dd" prefix-icon="el-icon-date"
                                    class="elegant-picker">
                                    <template #prefix>
                                        <i class="el-icon-date icon-blue"></i>
                                    </template>
                                </el-date-picker>
                            </div>
                        </el-col>

                        <!-- 时间选择 -->
                        <el-col :span="12">
                            <div class="picker-container">
                                <el-time-select v-model="deliveryTime" :picker-options="timeOptions" placeholder="选择时间"
                                    prefix-icon="el-icon-time" class="elegant-picker">
                                    <template #prefix>
                                        <i class="el-icon-time icon-blue"></i>
                                    </template>
                                </el-time-select>
                            </div>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="beforeCancle" class="cancel-btn">
                    <i class="el-icon-close"></i> 取 消
                </el-button>
                <el-button type="primary" @click="buildDateTime" class="confirm-btn">
                    <i class="el-icon-check"></i> 确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getPageOrder, cancelOrder, updateDeliveryTime, deleteOrderInfo } from "@/api/user/order";
import moment from 'moment';
export default {

    data() {
        return {
            currentPage: 1,
            pageSize: 5,
            total: 100,
            billNum: "",
            courierCompany: "",
            formLabelWidth: "140px",
            list: [], // 分页查询返回的数据
            listLoading: true,
            detailDialogVisible: false, //详情的对话框
            deliveryTimeDialogVisible: false, //修改时间的对话框
            detailForm: [], // 详情对话框的数据
            deliveryDate: "", // 日期
            deliveryTime: "", // 时间
            daliveryDateTime: "",
            dateOptions: {
                disabledDate: (time) => {
                    const now = moment()
                    const cutoffHour = 20 // 晚上8点
                    const currentHour = now.hour()

                    // 如果当前时间晚于20点，最早可选明天
                    const minDate = currentHour >= cutoffHour
                        ? now.clone().add(1, 'days').startOf('day')
                        : now.clone().hour(cutoffHour).isAfter(now)
                            ? now.clone().startOf('day')
                            : now.clone().add(1, 'days').startOf('day')

                    // 最大可选大后天
                    const maxDate = now.clone().add(3, 'days').endOf('day')

                    return time < minDate || time > maxDate
                }
            },
            timeOptions: {
                start: '08:00',
                end: '22:00',
                step: '00:30',
                minTime: this.getMinTime()
            }

        };
    },
    created() {
        this.fetchData();
    },

    watch: {
        deliveryDate(newVal) {
            this.timeOptions.minTime = this.getMinTime()
        },
        'deliveryDate': {
            handler(newVal) {
                this.handleDateTimeChange(newVal, this.deliveryTime)
            }
        },
        'deliveryTime': {
            handler(newVal) {
                this.handleDateTimeChange(this.deliveryDate, newVal)
            }
        }
    },
    methods: {
        handleDateTimeChange(date, time) {
            if (date && time) {
                // 使用moment处理时间拼接
                const combined = moment(`${date} ${time}`).format('YYYY-MM-DD HH:mm:ss')

                // 如果需要严格校验时间有效性
                if (!moment(combined).isValid()) {
                    console.error('无效的时间组合')
                    return
                }

                // 更新到目标字段
                this.daliveryDateTime = combined

                // 如果直接需要修改原字段（根据业务需求）
                // this.substitutionData.deliveryTime = combined
            } else {
                // 清空逻辑（可选）
                this.daliveryDateTime = null
            }
        },
        getMinTime() {
            if (!this.deliveryDate) return '08:00'
            const isToday = moment(this.deliveryDate).isSame(moment(), 'day')
            if (!isToday) return '08:00'

            const now = moment()
            const currentMinutes = now.minutes()
            let nextHour = now.hour()

            // 计算最近的可选时间点
            if (currentMinutes > 30) {
                nextHour += 1
                return `${nextHour.toString().padStart(2, '0')}:00`
            } else {
                return `${nextHour.toString().padStart(2, '0')}:${currentMinutes < 30 ? '30' : '00'}`
            }
        },
        fetchData() {
            this.listLoading = true;
            getPageOrder({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                billNum: this.billNum,
                courierCompany: this.courierCompany,
            }).then((res) => {
                this.list = res.data.dataList;
                this.total = res.data.total;
                this.listLoading = false;
            });
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.fetchData();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            this.fetchData();
        },

        // 处理通过复选框选中的数据
        handleSelectionChange(val) {
            this.multipleSelection = []
            // val是选中的行的数据组成的数组
            for (var i = 0; i < val.length; i++) {
                // 将选中的id存入数组
                this.multipleSelection.push(val[i].id)
            }
            // console.log(this.multipleSelection)
        },
        handleEdit(index, row) {
            this.detailDialogVisible = true
            this.detailForm = row

        },
        searchInfo() {
            this.fetchData()
        },
        indexMethod(index) {
            return index + 1
        },
        async handleDelete(index, row) {
            const deliveryTime = new Date(row.deliveryTime);  // 将 deliveryTime 字符串转为 Date 对象
            const currentTime = new Date();  // 获取当前时间
            const oneHourBefore = new Date(currentTime.getTime() - 60 * 60 * 1000);
            // 使用 getTime() 进行比较
            if (deliveryTime.getTime() < oneHourBefore.getTime() && row.status != 2) {
                this.$message.warning("配送前一个小时不能取消订单！");
            } else if (row.status == 2) {
                // 如果订单状态是已完成，可以删除订单记录
                await this.$confirm('确定要删除吗？', '提示', { type: 'warning' })
                deleteOrderInfo({ id: row.id }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.fetchData()
                    }
                })
            } else {
                // 否则只能取消订单
                await this.$confirm('确定要取消该订单吗？', '提示', { type: 'warning' })
                cancelOrder({ id: row.id }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: '取消订单成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.fetchData()
                    }
                })
            }

        },
        editDeliveryTime() {
            const deliveryTime = new Date(this.detailForm.deliveryTime);  // 将 deliveryTime 字符串转为 Date 对象
            const currentTime = new Date();  // 获取当前时间
            const oneHourBefore = new Date(currentTime.getTime() - 60 * 60 * 1000);
            // 使用 getTime() 进行比较
            if (deliveryTime.getTime() < oneHourBefore.getTime()) {
                this.$message.warning("配送前两个个小时不能修改配送时间！");
            } else {
                this.deliveryTimeDialogVisible = true
            }
        },
        beforeCancle() {
            this.date = ""
            this.time = ""
            this.deliveryTimeDialogVisible = false
        },
        buildDateTime() {
            this.detailForm.deliveryTime = this.daliveryDateTime;  // 更新到 detailForm
            this.deliveryTimeDialogVisible = false;
        },
        sure() {
            updateDeliveryTime({
                orderId: this.detailForm.id,
                deliveryTime: this.detailForm.deliveryTime
            }).then(res => {
                if (res.code == 200) {
                    this.detailDialogVisible = false;  // 关闭详情对话框
                }
            })
        },
    },
};
</script>

<style lang="scss" scoped>
.order-detail-dialog {
    .compact-form {
        .info-block {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #eee;

            .block-header {
                font-size: 15px;
                font-weight: 600;
                color: #2c3e50;
                margin-bottom: 15px;
                padding-bottom: 8px;
                border-bottom: 2px solid #eaeefb;
            }
        }

        .compact-item {
            margin-bottom: 12px;

            ::v-deep .el-form-item__label {
                padding-bottom: 2px;
                color: #6c757d;
                font-size: 13px;
            }
        }

        .info-input {
            ::v-deep .el-input__inner {
                background-color: #fff;
                border-color: #e4e7ed;
                color: #495057;

                &:hover {
                    border-color: #c0c4cc;
                }
            }
        }

        .delivery-info {
            .info-tag {
                margin-bottom: 8px;

                .label {
                    color: #6c757d;
                    margin-right: 5px;
                }
            }
        }

        .remark-box {
            ::v-deep .el-textarea__inner {
                background-color: #fdfdfd;
                border-color: #e4e7ed;
            }
        }

        .full-width {
            width: 100%;
        }
    }

    .dialog-footer {
        padding-top: 15px;
        border-top: 1px solid #eee;
    }
}
.delivery-time-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    .el-dialog__title {
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .time-picker-group {
    margin: 20px 0;

    .picker-container {
      position: relative;
      border-radius: 6px;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
      }

      .elegant-picker {
        width: 100%;

        ::v-deep .el-input__inner {
          height: 40px;
          border: 1px solid #dcdfe6;
          border-radius: 6px;
          transition: border-color 0.3s;

          &:hover {
            border-color: #409EFF;
          }

          &:focus {
            border-color: #409EFF;
            box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
          }
        }

        .icon-blue {
          color: #409EFF;
          font-size: 16px;
          margin-left: 8px;
        }
      }
    }
  }

  .dialog-footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;

    .cancel-btn {
      padding: 10px 20px;
      border-color: #dcdfe6;
      &:hover {
        color: #409EFF;
        border-color: #c6e2ff;
        background: #ecf5ff;
      }
    }

    .confirm-btn {
      padding: 10px 25px;
      background: #67c23a;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        background: #85ce61;
        box-shadow: 0 2px 12px rgba(103, 194, 58, 0.3);
      }
    }
  }
}

</style>